package com.linkq.ipinyin.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import com.alibaba.fastjson.JSONObject;
import com.linkq.ipinyin.model.Customer;
import com.linkq.ipinyin.service.CustomerService;
import com.linkq.ipinyin.vo.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.Objects;

/**
 * @FileName CustomerController
 * @Description
 * @Author wangpeng
 * @date 2024-12-10
 **/

@RestController
@RequestMapping("customer")
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @GetMapping("/getUserByAppleAppId/{appleAppId}")
    public ResultInfo getUserByAppleAppId(@PathVariable(value = "appleAppId") String appleAppId) {
        return customerService.getUserByAppleAppId(appleAppId);
    }

    @PostMapping("register")
    public ResultInfo register(@RequestBody Customer customer) {
        return customerService.register(customer);
    }

    @PostMapping("login")
    public JSONObject login(@RequestBody Customer customer) {
        SaTokenInfo token = customerService.login(customer);
        JSONObject result = new JSONObject();
        if (!Objects.isNull(token)) {
            Customer user = customerService.getUser();
            result.put("code", 200);
            result.put("success", true);
            result.put("msg", "登录成功");
            result.put("token", token);
            result.put("user", user);
        } else {
            result.put("code", 304);
            result.put("success", false);
            result.put("msg", "用户不存在");
        }
        return result;
    }

    @PostMapping("editPassword")
    public ResultInfo editPassword(@RequestBody Customer customer) {
        return customerService.editPassword(customer);
    }

    @PostMapping("edit")
    public ResultInfo edit(@RequestBody Customer customer) {
        return customerService.edit(customer);
    }

    @PostMapping("logOut")
    public void logOut() {
        customerService.logOut();
    }

    @PostMapping("/trial")
    public ResultInfo trail(@RequestBody Customer customer) {
        Customer original = customerService.selectById(customer.getId());
        if (null == original) {
            return ResultInfo.error("用户不存在");
        }
        original.setVipType(3);
        original.setExpireTime(Date.from(LocalDateTime.now().plusMonths(1).atZone(ZoneId.systemDefault()).toInstant()));
        customerService.updateById(original);
        return ResultInfo.success(original);
    }
}
